﻿using Newtonsoft.Json.Linq;
using TrinityAPI.Base.Tools;

namespace TrinityAPI.Base
{
    public class ModifyDataset : IAction
    {
        public JToken Invoke(JObject dataset, params JToken[] args)
        {
            if (args.Length > 0)
            {
                if (args[0] is JObject)
                {
                    int count = 0;
                    foreach (var item in (JObject)args[0])
                    {
                        JToken value = Utils.GetValueByPath(item.Key, dataset);
                        if (value?.Parent is JProperty)
                        {
                            ((JProperty)value.Parent).Value = item.Value;
                            count++;
                        }
                        else if (value?.Parent is JArray)
                        {
                            int index = -1;
                            if (int.TryParse(value.Path.Substring(value.Path.LastIndexOf('[') + 1).TrimEnd(']'), out index))
                            {
                                ((JArray)value.Parent)[index] = item.Value;
                                count++;
                            }
                        }
                    }
                    return count;
                }
                else if (args.Length == 2 && args[0]?.Type == JTokenType.String)
                {
                    JToken value = Utils.GetValueByPath(args[0].ToString(), dataset);
                    if (value?.Parent is JProperty)
                    {
                        ((JProperty)value.Parent).Value = args[1];
                        return 1;
                    }
                    else if (value?.Parent is JArray)
                    {
                        int index = -1;
                        if (int.TryParse(value.Path.Substring(value.Path.LastIndexOf('[') + 1).TrimEnd(']'), out index))
                        {
                            ((JArray)value.Parent)[index] = args[1];
                            return 1;
                        }
                    }
                }
            }
            return 0;
        }
    }
}
